
import { defineStore } from "pinia";
import { defineAsyncComponent } from "vue";
 
export default defineStore("user", {
  state() {
    return {
      userList: [] as IUser[],
      menu : [],
      asyncRouters:[]
    };
  },
  actions: {
    // getList() {
    // },
    setMenu(menu: any){
      this.menu = menu
      this.setRouters()
    },
    setUserRouter(){
      return new Promise((resolve, reject) => {
        resolve(this.asyncRouters)
      })
    },
    setRouters(){
      const copyRouter = JSON.parse(JSON.stringify(this.menu))
      this.asyncRouters = filterAsyncRouters(copyRouter)
    }
  },
  persist: {
    enabled: true , // 这个配置代表存储生效，而且是整个store都存储
  }
});

//此处需要改造 必须要用递归来完成
// function filterAsyncRouters(routers:any){  
//   routers.forEach((element:any) => {
//     element.component = loadView(element.component)
//     if(element.children && element.children.length){
//       element.children.forEach((i:any)=>{
//         i.component = loadView(i.component)
//         if(i.children && i.children.length){
//           i.children.forEach((j:any)=>{
//             j.component = loadView(j.component)
//           })
//         }
//       })
//       // filterAsyncRouters(element.children)
//     }
//   });
//   return routers
// }

//使用递归来完成
function filterAsyncRouters(routers:any){  
  return routers.map((element:any) => {
    const o = {
      component: element.component,
			children: element.children,
			path: element.path,
      name:element.name
    }
    o.component = loadView(o.component)
    if (o.children && o.children.length) {
			o.children = filterAsyncRouters(o.children)
		}
    if (o.path === '/') {
			o.redirect = '/home'
		}
    return o 
  });
}

function loadView(view:any) {
	// 这里需要注意一下 vite+vue3 要用 defineAsyncComponent 才能拼接成功 不然会一直报错找不到模块  加上/* @vite-ignore */ 可以不显示警告  
    if(view) {
      return () => defineAsyncComponent(() => import(/* @vite-ignore */`/src/views/${view}.vue`))
    }
}